<script setup>
import { ref, reactive } from 'vue'
import { showMsg } from '@/assets/js/utils'
import config from '@/assets/js/config'
import {
    getProduct,
    getDeviceType,
    addOrUpdateDevice,
    getDeviceDetail,
} from '@/assets/api/device'
import { useRoute } from 'vue-router'
const route = useRoute()
const props = defineProps({
    hasHidden: {
        type: Boolean,
        required: true,
    },
    deviceId: {
        type: String,
        default: '',
    },
    deviceClassId: {
        type: String,
        default: '',
    },
    deviceClassify: {
        type: String,
        default: '',
    },
    deviceData: {
        type: Object,
        default() {
            return {}
        },
    },
})
const emits = defineEmits(['success'])
const productList = ref([])
const typeList = ref([])
const { query, params } = route
const deviceClassIdRoute = ref(
    params.deviceClass ? params.deviceClass : query.device_class
)
function getData() {
    getProduct({
        deviceClassId: props.deviceClassId || deviceClassIdRoute.value,
    }).then((res) => {
        productList.value = res.data
    })
    getDeviceType({
        deviceClassId: props.deviceClassId || deviceClassIdRoute.value,
    }).then((res) => {
        typeList.value = res.data
        typeList.value.push({
            device_class_id: '',
            id: '1111',
            name: '接入网关',
        })
    })
}
getData()
const previewImageUrl = ref('')
const previewVisible = ref(false)
const fileList = ref([])
function handlePictureCardPreview(file) {
    previewImageUrl.value = file.url
    previewVisible.value = true
}
function handleUploadSuccess(res, file) {
    console.log(res, file)
    fileList.value.push({ url: res.data })
}
function handleRemove(file, fileList) {
    console.log(file, fileList)
    fileList.value = fileList.value.map((item) => {
        return { name: item.name, url: item.url }
    })
}
// 初始化form
const trans_device_code = reactive(route.query.number)
const newForm = reactive({})
function initForm() {
    if (props.deviceData) {
        const { ip, port } = props.deviceData
        Object.assign(newForm, {
            cameraIp: ip,
            cameraPort: port,
            number: ip,
        })
    }
    if (!props.deviceId) return
    getDeviceDetail({ id: props.deviceId }).then(({ data }) => {
        const {
            id,
            name,
            number,
            install_time,
            position,
            alarm_phone,
            install_person,
            img,
            install_person_phone,
            remark,
            device_type,
            product_id,
            control,
            // ip,
        } = data
        Object.assign(newForm, {
            id,
            name,
            number,
            installTime: install_time,
            position,
            alarmPhone: alarm_phone,
            installPerson: install_person,
            img,
            installPersonPhone: install_person_phone,
            remark,
            deviceType: device_type,
            productId: product_id,
            control,
            // ip,
        })
        if (img) {
            fileList.value = img.split(',').map((item) => {
                return { url: item }
            })
        }
        //
        if (
            device_type == 2001 ||
            device_type == 3001 ||
            device_type == 2002 ||
            device_type == 2003
        ) {
            const { camera_account, camera_password, camera_ip, camera_port } =
                data
            Object.assign(newForm, {
                cameraAccount: camera_account,
                cameraPassword: camera_password,
                cameraIp: camera_ip,
                cameraPort: camera_port,
            })
        }
    })
}
initForm()
// 新增
const newFormRef = ref()
function submitAction() {
    newFormRef.value.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            const params = Object.assign(
                {
                    deviceClassify: props.deviceClassify,
                    deviceClass:
                        props.deviceClassId || deviceClassIdRoute.value,
                    ...(trans_device_code && { trans_device_code }),
                    is_children: trans_device_code ? 1 : 2,
                },
                newForm
            )
            if (fileList.value.length > 0) {
                params.img = fileList.value.map((item) => item.url).join(',')
            }
            addOrUpdateDevice(params).then(() => {
                showMsg('保存成功')
                emits('success')
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
defineExpose({ submitAction })
const controlRadio = ref(false)
function handleSelRadio(val) {
    //无的时候单选框禁改
    if (val == 0 && newForm.name) controlRadio.value = true
}
</script>
<template>
    <el-form ref="newFormRef" :model="newForm" label-width="130px">
        <el-form-item
            label="设备名称："
            prop="name"
            :rules="[
                {
                    required: true,
                    message: '请输入',
                    trigger: 'change',
                },
            ]"
        >
            <el-input
                placeholder="请输入"
                v-model.trim="newForm.name"
            ></el-input>
        </el-form-item>
        <el-form-item
            label="设备编号："
            prop="number"
            :rules="[
                {
                    required: true,
                    message: '请输入',
                    trigger: 'change',
                },
            ]"
        >
            <el-input
                placeholder="请输入"
                v-model.trim="newForm.number"
            ></el-input>
        </el-form-item>
        <el-form-item
            label="设备类型："
            prop="deviceType"
            :rules="[
                {
                    required: true,
                    message: '请选择',
                    trigger: 'change',
                },
            ]"
        >
            <el-select
                class="full"
                v-model="newForm.deviceType"
                placeholder="请选择"
            >
                <el-option
                    :label="item.name"
                    :value="item.id"
                    v-for="(item, key) in typeList"
                    :key="key"
                    :disabled="trans_device_code ? item.id == '1111' : false"
                ></el-option>
            </el-select>
        </el-form-item>

        <el-form-item
            label="安装日期："
            prop="installTime"
            :rules="[
                {
                    required: true,
                    message: '请选择',
                    trigger: 'change',
                },
            ]"
        >
            <el-date-picker
                v-model="newForm.installTime"
                placeholder="请选择"
                type="date"
                value-format="YYYY-MM-DD"
            >
            </el-date-picker>
        </el-form-item>
        <el-form-item
            label="安装位置："
            prop="position"
            :rules="[
                {
                    required: true,
                    message: '请输入安装位置',
                    trigger: 'change',
                },
            ]"
        >
            <el-input
                placeholder="请输入"
                v-model.trim="newForm.position"
            ></el-input>
        </el-form-item>
        <el-form-item label="控制功能" prop="control" v-if="props.hasHidden">
            <el-radio-group v-model="newForm.control" @change="handleSelRadio">
                <el-radio label="1" :disabled="controlRadio">有 </el-radio>
                <el-radio label="0" :disabled="controlRadio"> 无 </el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="设备图片：" v-if="props.hasHidden">
            <el-upload
                class="upload-image"
                :action="config.uploadUrl"
                list-type="picture-card"
                :file-list="fileList"
                accept="image/*"
                :on-success="handleUploadSuccess"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
            >
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>
        </el-form-item>
        <el-form-item
            label="产品："
            prop="productId"
            :rules="[
                {
                    required: true,
                    message: '请选择产品',
                    trigger: 'change',
                },
            ]"
        >
            <el-select
                class="full"
                v-model="newForm.productId"
                placeholder="请选择"
            >
                <el-option
                    :label="item.name"
                    :value="item.id"
                    v-for="(item, key) in productList"
                    :key="key"
                ></el-option>
            </el-select>
        </el-form-item>
        <!-- <el-form-item label="报警电话：">
      <el-input placeholder="请输入报警电话（多个电话请使用英文逗号隔开）" v-model.trim="newForm.alarmPhone"></el-input>
    </el-form-item>
    <el-form-item label="安装人员：" prop="installPerson" :rules="[
                {
                    required: true,
                    message: '请输入',
                    trigger: 'change',
                },
            ]">
      <el-input placeholder="请输入" v-model.trim="newForm.installPerson"></el-input>
    </el-form-item>
    <el-form-item label="安装人员电话：" prop="installPersonPhone" :rules="[
                {
                    required: true,
                    message: '请输入',
                    trigger: 'change',
                },
            ]">
      <el-input placeholder="请输入" v-model.trim="newForm.installPersonPhone"></el-input>
    </el-form-item> -->
        <template
            v-if="newForm.deviceType == 2001 || newForm.deviceType == 3001"
        >
            <el-form-item
                :label="`${newForm.deviceType == 2001 ? '摄像头' : ''}账号：`"
                prop="cameraAccount"
                :rules="[
                    {
                        required: true,
                        message: '请输入',
                        trigger: 'change',
                    },
                ]"
            >
                <el-input
                    placeholder="请输入"
                    v-model.trim="newForm.cameraAccount"
                ></el-input>
            </el-form-item>
            <el-form-item
                :label="`${newForm.deviceType == 2001 ? '摄像头' : ''}密码：`"
                prop="cameraPassword"
                :rules="[
                    {
                        required: true,
                        message: '请输入',
                        trigger: 'change',
                    },
                ]"
            >
                <el-input
                    placeholder="请输入"
                    type="password"
                    v-model.trim="newForm.cameraPassword"
                ></el-input>
            </el-form-item>
            <el-form-item
                :label="`${newForm.deviceType == 2001 ? '摄像头' : ''}IP：`"
                prop="cameraIp"
                :rules="[
                    {
                        required: true,
                        message: '请输入',
                        trigger: 'change',
                    },
                ]"
            >
                <el-input
                    placeholder="请输入"
                    v-model.trim="newForm.cameraIp"
                ></el-input>
            </el-form-item>
            <el-form-item
                :label="`${newForm.deviceType == 2001 ? '摄像头' : ''}端口：`"
                prop="cameraPort"
                :rules="[
                    {
                        required: true,
                        message: '请输入',
                        trigger: 'change',
                    },
                ]"
            >
                <el-input
                    placeholder="请输入"
                    v-model.trim="newForm.cameraPort"
                ></el-input>
            </el-form-item>
        </template>
        <el-form-item
            v-if="newForm.deviceType == 2002 || newForm.deviceType == 2003"
            label="IP"
            prop="cameraIp"
            :rules="[
                {
                    required: true,
                    message: '请输入',
                    trigger: 'change',
                },
            ]"
        >
            <el-input
                placeholder="请输入"
                v-model.trim="newForm.cameraIp"
            ></el-input>
        </el-form-item>
        <el-form-item label="备注：">
            <el-input
                placeholder="请输入"
                type="text"
                v-model.trim="newForm.remark"
            ></el-input>
        </el-form-item>
    </el-form>
</template>
